package com.sky.task;

import com.sky.context.BaseContext;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/*
    创建定时任务类，定时处理订单状态
 */
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    /*
        处理超时订单方法(十五分钟未支付超时取消订单),每分钟触发一次
     */
    @Scheduled(cron = "0 * * * * ?") //-->每分钟进行一次
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processTimeoutOrder(){
        //  select * from orders where status=1 and order_time < (当前时间-15分钟)
        Integer status=1;
        LocalDateTime time=LocalDateTime.now().plusMinutes(-15);
        List<Orders> byStatusAndOrderTimeLT = orderMapper.getByStatusAndOrderTimeLT(status, time);
        if (byStatusAndOrderTimeLT!=null&&byStatusAndOrderTimeLT.size()>0)
        {
            for (Orders orders : byStatusAndOrderTimeLT) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }

    }
    /*
        商家未点击已完成订单，自动完成
        每天凌晨一点触发一次，将昨日一直派送中未点击已完成订单全部自动实现
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        LocalDateTime time=LocalDateTime.now().plusHours(-1);
        List<Orders> list=orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS,time);
        if(list!=null&&list.size()>0)
        {
            for (Orders orders:list)
            {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
